<script setup lang="ts">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, defineEmits } from 'vue'
import { FormSchema } from '@/types/form'
import { OrgData } from "@/api/org/types";
import { ElMessage, ElUpload, ElIcon } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { useIcon } from '@/hooks/web/useIcon'

const icons = {
  plusIcon: useIcon({ icon: 'ph:plus-bold' })
}
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<OrgData>>,
    default: () => null
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  }
})

const rules = reactive({})

const { register, methods, elFormRef } = useForm({
  schema: props.formSchema
})

const emit = defineEmits(["uploadedLicense"]);

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    const { setValues } = methods
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

const handleSuccess: UploadProps['onSuccess'] = (response) => {
  emit('uploadedLicense', response.data.url);
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const isImage = ['image/jpeg', 'image/png'].includes(rawFile.type);
  const isLt300K = rawFile.size / 1024 < 300;

  if (!isImage) {
    ElMessage.error('只能上传JPG和PNG格式');
    return false;
  }
  if (!isLt300K) {
    ElMessage.error('图片大小不能超过 300KB!');
    return false;
  }
  return isImage && isLt300K;
}



defineExpose({
  elFormRef,
  getFormData: methods.getFormData,
  addSchema: methods.addSchema,
  delSchema: methods.delSchema
})
</script>

<template>
  <Form :rules="rules" @register="register">
    <template #license="form">
      <ElUpload class="avatar-uploader" action="/api/upload/file" :show-file-list="false" :on-success="handleSuccess"
        accept="image/png, image/jpeg" :before-upload="beforeAvatarUpload">
        <img v-if="form['license']" :src="form['license']" class="avatar" />
        <Icon v-else icon="ph:plus-bold" class="cursor-pointer avatar-uploader-icon" />
        <template #tip>
          <div class="el-upload__tip !text-red-500">
            图片大小不能超过300KB
          </div>
        </template>
      </ElUpload>
    </template>
  </Form>
</template>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>